<?php

include_once(dirname(__FILE__).'/service.php');
include_once(dirname(__FILE__).'/classes_database/services.database.sysshared.php');

class System_Functions extends Service
{
    private  $db = null;

    public function System_Functions()
    {
        $this->db  =  DBSysShared::getInstance();
    }

    /**
    * @remotable
    */
    public function generateChallange($length = 40)
    {
        $this->getLogger()->debug('---- generateChallange ----');

        $challenge = "";
        $possible = "0123456789bcdfghjkmyz!#$%&?:.,";
        $i = 0;
        while ($i < $length)
        {
            $char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $challenge .= $char;
            $i++;
        }

        return $challenge;
    }

    /**
    * @remotable
    * @formHandler
    */
    public function login($form)
    {
        @session_start();
        $response = array();

        $this->getLogger()->debug('---- login ----');

        $user_info = $this->db->getUser($form['loginUsername']);

        $this->getLogger()->debug($user_info);

        // Si se produce el siguiente error quiere decir que no se había generado un challenge antes de llamar al login, esto puede ocurrir o porque no se paso por el index.php o porque estaba logueado con un usuario, y vuelvo a intentar hacer login sin hacer logout.
        if(!isset($_SESSION['challenge']))
        {
            $response['success'] = false;
            if( isset($_SESSION['logged']) && $_SESSION['logged'] == true )
            {
                $response['message'] = "Por favor desloguee.";
            }
            else
            {
                $response['message'] = "Desconocido.";    // Aunque si llegamos hasta acá yo creo que estas intentando hackearnos...
            }
        }
        else
        {

            if($user_info)
                $md5 = md5( $_SESSION['challenge'].$user_info['password_usr'] );

            if( empty($form['loginPassword']) || empty($form['loginUsername']) || !$user_info || $form['loginPassword']!=$md5 /*|| !$user_info['is_enabled_usr']*/ )
            {
                $response['success'] = false;
                $response['message'] = "Usuario o Contraseña no validos";
            }
            else
            {

                $response['success'] = true;
                $params = array();
                @session_unset();
                //@session_destroy();

                $_SESSION['id_usr'] = $user_info['id_usr'];
                $_SESSION['username_usr'] = $user_info['username_usr'];
                //$_SESSION['id_utp_usr']   = $user_info['id_utp_usr'];
                $_SESSION['logged'] = true;

                /*switch($user_info['id_utp_usr'])
                {
                    case _USERTYPE_ADMIN:
                        $_SESSION['name_clt'] = $user_info['username_usr'];
                        $_SESSION['surname_clt'] = '';
                        break;
                    case _USERTYPE_CLIENT:
                        $client_info = $this->db->getClient($user_info['id_usr']);
                        $_SESSION['id_clt'] = $client_info['id_clt'];
                        $_SESSION['name_clt'] = $client_info['name_clt'];
                        $_SESSION['surname_clt'] = $client_info['surname_clt'];
                        break;
                    default :
                        $response['success'] = false;
                        $response['message'] = "Desconocido";

                }
                $this->db->logUserAction($_SESSION['id_usr'],$_SERVER['REMOTE_ADDR'],'USER_LOGIN');*/
            }
        }

        if(!$response['success'])
        {
            @session_unset();
            $_SESSION['challenge'] = $this->generateChallange();
            $response['challenge'] = $_SESSION['challenge'];
        }

        return $response;
    }

    /**
    * @remotable
    */
    public function closeSession()
    {
        $this->getLogger()->debug('---- closeSession ----');

        $this->db->logUserAction($_SESSION['id_usr'],$_SERVER['REMOTE_ADDR'],'USER_LOGOUT');
        $this->getLogger()->debug("closeSession");
        @session_start();
        @session_regenerate_id(true);
        @session_unset();
        @session_destroy();
        return array('success' => true);
    }

    /**
    * @remotable
    * @formHandler
    */
    public function registerUser($form)
    {
        $this->getLogger()->debug('---- registerUser ----');

        // crea el usuario
        if($form['password_usr']!=$form['password_usr_again'])
            return array('success'=>false, 'error'=>'Las contraseñas no coinciden.');

        $this->db->StartTrans();
            
        $user_info = array(
            'username_usr' => $form['username_usr'],
            'password_usr' => md5($form['password_usr']),
            'id_utp_usr' => _USERTYPE_CLIENT
        );
        $id_usr = $this->db->executeInsert('sys_user_usr',$user_info,'id_usr');

        // crea el cliente
        $client_info = array(
            'id_usr_clt'  => $id_usr,
            'name_clt'    => $form['name_clt'],
            'surname_clt' => $form['surname_clt'],
            'address_clt' => $form['address_clt'],
            'phone_clt'   => $form['phone_clt'],
            'email_clt'   => $form['email_clt']/*,
            'cellphone_clt'   => $form['cellphone_clt'],
            'zipcode_usr'     => $form['zipcode_usr'],
            //'client_code_clt' => $form['client_code_clt'],    Averiguar si necesitan o quieren algun tipo de numeración especial para los clientes.
            'id_pro_clt'      => $form['id_pro_clt'],
            'id_loc_clt'      => $form['id_loc_clt']/**/
        );
        $id_usr_clt = $this->db->executeInsert('rcd_client_clt',$client_info,'id_clt');

        $this->db->CompleteTrans();
        
        return array('success'=>true);
    }

    /**
    * @remotable
    * @formHandler
    */
    public function changePassword($form)
    {
        $this->getLogger()->debug('---- changePassword ----');

        if($form['password_usr']!=$form['password_usr_again'])
            return array('success'=>false, 'error'=>'Las contraseñas no coinciden.');

        $user_info = array(
            'password_usr' => md5($form['password_usr'])
            // faltaría setear el datet_last_modified, aunque no estoy seguro si vale la pena por un cambio de password
        );

        $id_usr = $this->db->executeUpdate('sys_user_usr',$user_info,"id_usr=${_SESSION['id_usr']}");

        $this->db->logUserAction($_SESSION['id_usr'],$_SERVER['REMOTE_ADDR'],'USER_PASSWORD_CHANGED');

        return array('success'=>true);
    }

    /**
    * @remotable
    * @formHandler
    */
    public function updateClientInfo($form)
    {
        $this->getLogger()->debug('---- updateClientInfo ----');

        $client_info = array();

        if(isset($form['name_clt'])&&$form['name_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['name_clt'] = $form['name_clt'];

        if(isset($form['surname_clt'])&&$form['surname_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['surname_clt'] = $form['surname_clt'];

        if(isset($form['address_clt'])&&$form['address_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['address_clt'] = $form['address_clt'];

        if(isset($form['phone_clt'])&&$form['phone_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['phone_clt'] = $form['phone_clt'];

        if(isset($form['email_clt'])&&$form['email_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['email_clt'] = $form['email_clt'];

        if(isset($form['cellphone_clt'])&&$form['cellphone_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['cellphone_clt'] = $form['cellphone_clt'];

        if(isset($form['zipcode_usr'])&&$form['zipcode_usr']!=null&&!empty($form['id_loc_clt']))
            $client_info['zipcode_usr'] = $form['zipcode_usr'];

        if(isset($form['id_pro_clt'])&&$form['id_pro_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['id_pro_clt'] = $form['id_pro_clt'];

        if(isset($form['id_loc_clt'])&&$form['id_loc_clt']!=null&&!empty($form['id_loc_clt']))
            $client_info['id_loc_clt'] = $form['id_loc_clt'];

        if(!empty($client_info))
        {
            $client_info['datet_lastmodified_usr'] = date("Y-m-d H:i:s").".001";
            $id_usr_clt = $this->db->executeUpdate('rcd_client_clt',$client_info,"id_usr_clt=${_SESSION['id_usr']}");
        }
            

        return array('success'=>true);
    }

}
?>